package com.java.service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.java.dao.NguoidungDAO;
import com.java.mapbean.Nguoidung;

@SuppressWarnings("deprecation")
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private NguoidungDAO nguoidungDao;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        nguoidungDao = new NguoidungDAO();
        Nguoidung nguoidung = nguoidungDao.findUsername(username);

        if (nguoidung == null) {
            throw new UsernameNotFoundException("user not found");
        }

        String uname = nguoidung.getUsername();
        String pword = nguoidung.getPassword();
        boolean enabled = nguoidung.getStatus()==1?true:false;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;


        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new GrantedAuthorityImpl(nguoidung.getQuyen().getTenquyen()));
        return new User(uname, pword, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);
    }
}
